﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Web;

/// <summary>
/// Summary description for Mail.
/// The file App_Data/mail.txt
/// smtpserver=servername
/// username=username
/// password=password
/// website=website in order to identify this.
/// from=default from email address
/// to=default to email address
/// </summary>
public static class Mail
{

	public static void Simple(string subject, string body, string to = null)
	{
		if (to == null)
			to = Settings.SystemMailSettings.To;
		MailMessage message = new MailMessage();
		message.From = new MailAddress(Settings.SystemMailSettings.From, Settings.SystemMailSettings.FromName);
		if(to != null)
			message.To.Add(new MailAddress(to));
		else
			message.To.Add(new MailAddress(to, Settings.SystemMailSettings.ToName));
		message.Subject = subject;
		message.Body = body;
		SmtpClient smtp = new SmtpClient(Settings.SystemMailSettings.SmtpServer);
		smtp.Credentials = new System.Net.NetworkCredential(Settings.SystemMailSettings.UserName, Settings.SystemMailSettings.Password);
		smtp.Port = 25;
		smtp.EnableSsl = false;
		smtp.Send(message);
	}

	public static void UnauthorizedAccess()
	{
		var request = HttpContext.Current.Request;
		string body = "Someone made an unauthorized access from the machine at " + request.ServerVariables["REMOTE_ADDR"] + ".  ";
		body+="at " + DateTime.Now.ToString() + ".";
		Simple(Settings.SystemMailSettings.Website + " unauthorized access", body);
	}

	public static void WebsiteError()
	{
		var body = "An error occurred on the website: " + HttpContext.Current.Request.Url.AbsoluteUri + "\n\n";
		var request = HttpContext.Current.Request;
		for (int i = 0; i < request.Params.Count; ++i)
			body += request.Params.Keys[i] + "=" + request.Params[i] + "\n";
		body += "URL Referrer:" + request.UrlReferrer + "\n";
		var subject = "Website error on " + request.Url.DnsSafeHost;
		Simple(subject, body);
	}

}